package pers.mihao.quickstream.common.util;

import lombok.extern.slf4j.Slf4j;
import pers.mihao.quickstream.common.exception.BaseException;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author mihao
 * @version 1.0
 * @since 2021\1\10 0010 16:56
 */
@Slf4j
public class FileUtil {

    /**
     * 创建文件
     *
     * @param filePath 文件路径
     * @param bytes    文件流
     */
    public static void createFile(String filePath, byte[] bytes) throws IOException {
        Path path = Paths.get(filePath);
        createDir(filePath);
        Files.write(path, bytes);
    }

    public static String getFilePath(String... paths) {
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < paths.length; i++) {
            if (paths[i] == null || paths[i].length() == 0) {
                continue;
            }
            if (i > 0 && !paths[i].startsWith("\\") && !paths[i].startsWith("/")) {
                res.append(File.separator);
            }
            res.append(paths[i]);
            if (paths[i].endsWith("\\") || paths[i].endsWith("/")) {
                res.setLength(res.length() - 1);
            }
        }
        return res.toString();
    }

    public static String getDirPath(String... paths) {
        return getFilePath(paths) + File.separator;
    }

    /**
     * 创建文件
     *
     * @param filePath 文件路径
     */
    public static void createFile(String filePath, InputStream inputStream) throws IOException {
        try (OutputStream os = Files.newOutputStream(newFile(filePath).toPath())) {
            int bytesRead;
            int bytes = 8192;
            byte[] buffer = new byte[bytes];
            while ((bytesRead = inputStream.read(buffer, 0, bytes)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            inputStream.close();
        } catch (Exception e) {
            throw new BaseException("createFile " + filePath + " error");
        }
    }

    public static String getFileSuffix(String fileName) {
        if (StringUtil.isBlack(fileName)) {
            return "";
        }
        int index = fileName.lastIndexOf(".");
        if (index == -1 || index == fileName.length() - 1) {
            throw new BaseException("GetFile " + fileName + " Suffix Max Not Be Null");
        }
        return fileName.substring(index + 1);
    }

    public static String getFilePath(String fileName) {
        int index = fileName.length() - 1;
        while (index > 0) {
            if (fileName.charAt(index) == '/' || fileName.charAt(index) == '\\') {
                break;
            }
            index--;
        }
        String filePath = fileName.substring(0, index + 1);
        return filePath;
    }

    public static String getFileName(String filepath) {
        int index = filepath.length() - 1;
        while (index > 0) {
            if (filepath.charAt(index) == '/' || filepath.charAt(index) == '\\') {
                break;
            }
            index--;
        }
        String fileName = filepath;
        if (index == 0 && (filepath.startsWith("/") || filepath.startsWith("\\"))) {
            fileName = filepath.substring(index + 1);
        }
        return fileName;
    }

    public static String getFileRealName(String filepath) {
        return getFileName(filepath).split("\\.")[0];
    }

    public static void createDir(String newFileNamePath) {
        createDir(Paths.get(newFileNamePath));
    }

    private static void createDir(Path path) {
        Path parentPath = path.getParent();
        if (!Files.exists(parentPath)) {
            try {
                createDir(parentPath);
                Files.createDirectory(parentPath);
            } catch (IOException e) {
                throw new BaseException(e);
            }
        }
    }


    public static File newFile(String newFileName) {
        File file = new File(newFileName);
        if (!file.getParentFile().exists()) {
            createDir(newFileName);
        }
        return file;
    }
}
